<template>
  <view class="container">

    <!-- 内容区域 -->
    <view scroll-y class="content">
      <!-- 项目信息 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">项目信息</text>
          <view @click="showBuildingInfo = !showBuildingInfo" class="collect-btn">收起 <image
              :class="['collect-btn-icon', showBuildingInfo ? '' : 'down']" src="@/static/images/right.png">
            </image>
          </view>
        </view>

        <view class="info-item">
          <text class="label">项目名称</text>
          <view class="value phone" @click="changeBuilding">{{ buildingInfo.name || '-' }}<uni-icons color="#0091FF"
              size="16" type="arrowright" /></view>
        </view>

        <view class="info-item" v-show="showBuildingInfo">
          <text class="label">要求时间</text>
          <view class="time-info">
            <text class="time-text" v-if="isDaytime">白天{{ buildingInfo.buildingExt &&
              buildingInfo.buildingExt.rescueDaytime ?
              buildingInfo.buildingExt.rescueDaytime : '30' }}分钟内({{ getRescueTime(buildingInfo.buildingExt &&
                buildingInfo.buildingExt.rescueDaytime ? buildingInfo.buildingExt.rescueDaytime : '30') }}前到达)</text>
            <text class="time-text" v-else>晚上{{ buildingInfo.buildingExt && buildingInfo.buildingExt.rescueNight ?
              buildingInfo.buildingExt.rescueNight : '30' }}分钟内({{ getRescueTime(buildingInfo.buildingExt &&
                buildingInfo.buildingExt.rescueNight ? buildingInfo.buildingExt.rescueNight : '30') }}前到达)</text>
          </view>
        </view>

        <view class="info-item" v-show="showBuildingInfo">
          <text class="label">联系人手机号</text>
          <view class="phone" @click="callPhoneNumber(buildingInfo.buildingContacts.phone)"
            v-if="buildingInfo.buildingContacts && buildingInfo.buildingContacts.phone">
            <image class="" src="@/static/images/callPhone.png">
            </image>{{ buildingInfo.buildingContacts.phone }}
          </view>
          <view class="value" v-else>
            -
          </view>
        </view>

        <view class="info-item" v-show="showBuildingInfo">
          <text class="label">项目地址</text>
          <text class="value">{{ buildingInfo.address || '-' }} </text>
        </view>
      </view>

      <!-- 电梯信息 -->
      <view class="section">
        <view class="section-title">电梯信息</view>

        <view class="form-item">
          <text class="required">*</text>
          <text class="label">电梯位置</text>
          <view class="radio-group">
            <view v-for="(item, index) in elevatorPositions" :key="index" class="radio-item"
              :class="{ active: selectedPosition === item.value }" @tap="selectPosition(item.value)">
              {{ item.label }}
            </view>
          </view>
        </view>

        <view class="form-item" v-if="selectedPosition == '已知'">
          <text class="required">*</text>
          <text class="label">具体位置</text>
          <view class="input-row" @click="chooseElevator">
            <input disabled="false" :always-embed="true" class="input" placeholder-style="color:#ccc" placeholder="请选择"
              v-model="elevatorItem.name" />

            <image class="arrow-right" src="@/static/images/repairFitting/bottom.png">

            </image>

          </view>
        </view>

        <view class="form-item" v-if="selectedPosition == '已知部分'">
          <text class="required">*</text>
          <text class="label">已知部分位置</text>
          <view class="input-row" @click="chooseUnit">
            <input disabled="false" :always-embed="true" class="input" placeholder-style="color:#ccc" placeholder="请选择"
              v-model="unitItem.label" />

            <image class="arrow-right" src="@/static/images/repairFitting/bottom.png">

            </image>

          </view>
        </view>

        <view class="form-item">
          <text class="required"></text>
          <text class="label">救援中工单</text>
          <view class="order-count">
            <view>{{ rescusHis.length }}单 </view>
            <view class="detail" @click="showHis" v-if="rescusHis.length > 0">详情</view>
          </view>
        </view>

        <view class="form-item">
          <text class="required"></text>
          <text class="label">救援楼层</text>
          <view class="floor-input">
            <text class="minus-btn" @tap="decreaseFloor">-</text>
            <input placeholder-style="color:#ccc" :always-embed="true" class="floor-value" placeholder="请输入/选择"
              v-model="formData.floor" type="number" maxlength="3" />
            <text class="plus-btn" @tap="increaseFloor">+</text>
          </view>
        </view>
      </view>

      <!-- 报警信息 -->
      <view class="section">
        <view class="section-title">报警信息</view>

        <view class="form-item">
          <text class="required">*</text>
          <text class="label">报警人</text>
          <input :always-embed="true" class="input" placeholder-style="color:#ccc" placeholder="请输入"
            v-model="formData.name" />
        </view>

        <view class="form-item">
          <text class="required">*</text>
          <text class="label">联系方式</text>
          <input :always-embed="true" class="input" maxlength="11" placeholder-style="color:#ccc" placeholder="请输入手机号"
            v-model="formData.phone" type="number" />
        </view>

        <view class="form-item">
          <text class="required">*</text>
          <text class="label">报警类型</text>
          <view class="radio-group">
            <view v-for="(item, index) in alarmTypes" :key="index" class="radio-item"
              :class="{ active: formData.trapType === item.value }" @tap="selectAlarmType(item.value)">
              {{ item.label }}
            </view>
          </view>
        </view>

        <view class="form-item">
          <text class="required">*</text>
          <text class="label">报警来源</text>

          <view class="input-row" @click="chooseOrgs">
            <input :always-embed="true" disabled class="input" placeholder-style="color:#ccc" placeholder="请选择"
              v-model="formData.trapFromValue" />
            <image class="arrow-down" src="@/static/images/repairFitting/bottom.png"></image>
          </view>

        </view>

        <view class="form-item">
          <text class="label">报警备注</text>
          <text class="optional">(选填)</text>
          <textarea class="textarea" placeholder-style="color:#ccc" placeholder="请输入备注内容" v-model="formData.trapDesc"
            maxlength="300"></textarea>
          <view class="char-count">{{ formData.trapDesc.length }}/300</view>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-buttons">
      <view class="btn-secondary" @tap="createOrder">仅创建工单</view>
      <view class="btn-primary" @tap="createAndDispatch">创建并调度</view>
    </view>

    <selectDrawer title="报警来源" ref="selectDrawer" label-key="dictValue" value-key="dictKey" @confirm="orgConfirm">
    </selectDrawer>
    <historyDrawer ref="historyDrawer"></historyDrawer>
    <elevatorDrawer ref="elevatorDrawer" @confirm="selectElevator"> </elevatorDrawer>
    <unitDrawer ref="unitDrawer" @confirm="selectUnit"></unitDrawer>
  </view>
</template>

<script>
import { getBuilding } from '@/apis/building.js';
import { getRescueElevatorList, createRescue, getRescueHis } from '@/apis/rescue.js';
import { dictionaryTree, getElevatorReles } from '@/apis/elevator.js';
import selectDrawer from './components/select-drawer.vue';
import historyDrawer from './components/history-drawer.vue';
import elevatorDrawer from './components/elevator-drawer.vue';
import unitDrawer from './components/unit-drawer.vue';
export default {
	components: { selectDrawer, historyDrawer, elevatorDrawer, unitDrawer },
	data() {
		return {
			unitItem: { label: '' },
			buildingId: '',
			buildingInfo: {},
			showBuildingInfo: true,
			elevators: [],
			tree: [],
			elevatorItem: { id: '', name: '' },
			// 报警来源
			orgs: [],

			formData: {
				// 报警来源
				trapFrom: '',
				trapFromValue: '',
				// 楼层
				floor: '',
				// 报警类型
				trapType: 0,

				// 报警人
				name: '',
				phone: '',
				// 备注
				trapDesc: ''
			},

			// 该项目救援中的工单
			rescusHis: [],

			selectedPosition: '已知',

			elevatorPositions: [
				{ label: '已知', value: '已知' },
				{ label: '已知部分', value: '已知部分' },
				{ label: '未知', value: '电梯未知' }
			],
			alarmTypes: [
				{ label: '困人', value: 0 },
				{ label: '伤人', value: 1 }
			],
			// 新增，判断当前是否为白天
			isDaytime: true,
		};
	},
	onLoad(ops) {
		console.log('user_dispatch', this.findRoute('user_dispatch'));
		console.log(ops);
		// 新增：判断当前时间是否为白天
		const now = new Date();
		const hour = now.getHours();
		this.isDaytime = hour >= 6 && hour < 18;
		if (ops.buildingId) {
			this.buildingId = ops.buildingId;
			this.getBuildingInfo();
			this.getRescueElevatorList();
			this.getTrapFroms();
		}
	},
	methods: {
		changeBuilding() {
			uni.showModal({
				title: '提示',
				content: '确定要切换项目吗？',
				success: res => {
					if (res.confirm) {
						uni.redirectTo({
							url: '/subpages/rescue/projectSelect'
						});
					}
				}
			});
		},
		// 确认选择部分位置
		selectUnit(res) {
			console.log('selectUnit', res);
			this.unitItem = res || { label: '' };
			let eleItem = null;
			if (res.lastNode) {
				// 最后节点,查询是否是电梯
				for (let i = 0; i < this.elevators.length; i++) {
					if (this.elevators[i].name == res.name) {
						eleItem = this.elevators[i];
						break;
					}
				}
			}

			if (eleItem) {
				this.elevatorItem = eleItem;
				this.getElevatorOrders(this.elevatorItem.id);
			} else {
				this.elevatorItem = { id: '', name: '' };
				this.rescusHis = [];
			}
		},
		// 确认选择电梯 
		selectElevator(res) {
			this.elevatorItem = res || { id: '', name: '' };
			if (this.elevatorItem.id) {
				this.getElevatorOrders(this.elevatorItem.id);
			} else {
				this.rescusHis = [];
			}
		},
		chooseElevator() {
			this.$refs.elevatorDrawer.open(this.elevators);
		},

		chooseUnit() {
			this.$refs.unitDrawer.open(this.tree);
		},

		// 查看救援工单列表
		showHis() {
			this.$refs.historyDrawer.open(this.rescusHis);
		},
		// 报警来源确定
		orgConfirm(res) {
			console.log(res);
			this.formData.trapFrom = res.valueKey;
			this.formData.trapFromValue = res.label;
		},
		// 打开报警选择弹窗
		chooseOrgs() {
			this.$refs.selectDrawer.open(this.orgs, this.formData.trapFrom);
		},
		// 获取该电梯救援中的工单
		getElevatorOrders(elevatorId) {
			getRescueHis({
				buildingId: this.buildingId,
				elevatorId
			}).then(res => {
				this.rescusHis = res.data || [];
			});
		},

		// 计算x分钟后的时间 xx点xx分
		getRescueTime(time = 30) {
			const now = new Date();
			const future = new Date(now.getTime() + Number(time) * 60000);
			const hours = future.getHours().toString().padStart(2, '0');
			const minutes = future.getMinutes().toString().padStart(2, '0');
			return `${hours}点${minutes}分`;
		},

		callPhoneNumber(phone) {
			if (phone) {
				uni.makePhoneCall({
					phoneNumber: phone
				});
			} else {
				uni.showToast({
					title: '无效的电话号码',
					icon: 'none'
				});
			}
		},
		getBuildingInfo() {
			getBuilding(this.buildingId).then(res => {
				this.buildingInfo = res.data || {};
			});
		},

		getRescueElevatorList() {
			// 电梯列表
			getRescueElevatorList({ buildingId: this.buildingId, size: 200 }).then(res => {
				let list = res.data.records || [];
				this.elevators = list.map(item => {
					return {
						id: item.elevatorId,
						name: item.elevatorAddress,
						type: 2
					};
				});
			});

			// 电梯楼栋单元树形
			getElevatorReles({
				buildingId: this.buildingId,
			}).then(res => {
				let tree = res.data || [];
				// 递归循环拼全称
				function addNameField(nodes, parentName = '', parentLabel = '') {
					if (!Array.isArray(nodes)) return;
					nodes.forEach(node => {
						let templateName = node.templateName != '无后缀' ? node.templateName : '';
						node.label = parentLabel + (parentLabel ? '>' : '') + (node.templateNum || '') + (templateName || '');
						node.name = parentName + (node.templateNum || '') + (templateName || '');
						node.type = 2;
						if (node.children && node.children.length > 0) {
							addNameField(node.children, node.name, node.label);
						} else {
							node.lastNode = true;
						}
					});
				}
				addNameField(tree);
				this.tree = tree;
			});
		},

		getTrapFroms() {
			dictionaryTree({
				code: 'rescue'
			}).then(res => {
				let data = res.data || [];
				for (let i = 0; i < data.length; i++) {
					if (data[i].dictKey == 1) {
						this.orgs = data[i].children;
						break;
					}
				}
			});
		},

		goBack() {
			uni.navigateBack();
		},
		selectPosition(value) {
			if (value == this.selectedPosition) {
				return;
			}

			this.elevatorItem = { id: '', name: '' };
			this.unitItem = { label: '' };

			this.rescusHis = [];
			this.selectedPosition = value;
		},
		selectAlarmType(value) {
			this.formData.trapType = value;
		},
		decreaseFloor() {
			let floor = parseInt(this.formData.floor || 0) - 1;
			// if (floor < 0) floor = 0;
			this.formData.floor = floor > 999 ? 999 : floor;
		},
		increaseFloor() {
			let floor = parseInt(this.formData.floor || 0) + 1;
			if (floor > 999) floor = 999;
			this.formData.floor = floor;
		},
		createOrder() {
			// 仅创建单
			if (!this.validateForm()) {
				return;
			}
			uni.showLoading({
				title: '提交中',
				mask: true,
			});

			let formData = JSON.parse(JSON.stringify(this.formData));
			if (this.selectedPosition != '电梯未知') {
				if (this.elevatorItem.id) {
					formData.elevatorId = this.elevatorItem.id;
					formData.address = this.elevatorItem.name;
				} else {
					formData.elevatorId = 0;
					formData.address = this.unitItem.label;
				}
			} else {
				formData.elevatorId = 0;
				formData.address = this.selectedPosition;
			}

			formData.buildingId = this.buildingId;
			createRescue(formData).then(res => {
				uni.hideLoading();
				// 仅创建工单逻辑
				uni.showToast({
					title: '创建工单成功'
				});
				setTimeout(() => {
					uni.redirectTo({
						url: '/subpages/rescue/rescueList?type=rescue'
					});
				}, 500);
			});
		},
		createAndDispatch() {
			// 创建并调度逻辑
			if (!this.validateForm()) {
				return;
			}
			uni.showLoading({
				title: '提交中',
				mask: true,
			});

			let formData = JSON.parse(JSON.stringify(this.formData));
			if (this.selectedPosition != '电梯未知') {
				if (this.elevatorItem.id) {
					formData.elevatorId = this.elevatorItem.id;
					formData.address = this.elevatorItem.name;
				} else {
					formData.elevatorId = 0;
					formData.address = this.unitItem.label;
				}
			} else {
				formData.elevatorId = 0;
				formData.address = this.selectedPosition;
			}

			const ifSendMyself =   this.findRoute('user_dispatch') ? false : true;
			formData.ifSendMyself = ifSendMyself;
			formData.buildingId = this.buildingId;
			createRescue(formData).then(res => {
				uni.hideLoading();
				let planId = res.data;
				if (ifSendMyself) {
					console.log('无调度权限-派给自己', planId);
					uni.redirectTo({
						url: `/subpages/rescue/rescueDetail?planId=${planId
						}&elevatorId=${formData.elevatorId > 0 ? formData.elevatorId : ''
						}`,
					});
				} else {
					uni.redirectTo({
						url: '/subpages/rescue/memberSelect?isCreate=1&planId=' + planId
              + '&buildingId=' + this.buildingId
              + '&elevatorId=' + this.elevatorItem.id
              + '&buildingName=' + this.buildingInfo.name
              + '&address=' + (formData.address)
					});
				}
			});
		},
		validateForm() {
			if ((!this.elevatorItem.id && !this.unitItem.id) && this.selectedPosition != '电梯未知') {
				uni.showToast({
					title: '请选择电梯位置',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.name) {
				uni.showToast({
					title: '请输入报警人',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.phone) {
				uni.showToast({
					title: '请输入联系方式',
					icon: 'none'
				});
				return false;
			}

			if (!this.formData.trapFromValue) {
				uni.showToast({
					title: '请选择报警来源',
					icon: 'none'
				});
				return false;
			}
			return true;
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  width: 750rpx;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 88rpx;
  padding: 0 30rpx;
  background-color: #333;
  color: #fff;

  .nav-left {
    width: 60rpx;
  }

  .nav-title {
    font-size: 34rpx;
    font-weight: 500;
  }

  .nav-right {
    display: flex;
    gap: 20rpx;
    width: 120rpx;
    justify-content: flex-end;
  }

  .iconfont {
    font-size: 40rpx;
    color: #fff;
  }
}

.content {
  flex: 1;
  padding-bottom: 120rpx;
}

.section {
  background-color: #fff;
  margin: 20rpx;

  padding: 20rpx;
  border-radius: 8rpx;
  padding-bottom: 0;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: baseline;

  }

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #3D3D3D;
    padding-bottom: 20rpx;
  }

  .collect-btn,
  .detail-btn {
    font-size: 28rpx;
    color: #0091FF;
    display: flex;
    align-items: center;

    &-icon {
      width: 30rpx;
      height: 28rpx;
      transform: rotate(-90deg);
      transition: .3s all;

    }

    .down {
      transform: rotate(90deg) !important;
    }
  }

  .arrow {
    margin-left: 10rpx;
  }
}

.order-count {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .detail {
    color: #0091FF;
  }
}

.info-item {
  padding-bottom: 30rpx;

  .label {
    font-size: 26rpx;
    color: #333;
    display: block;
    font-weight: bold;
    margin-bottom: 8rpx;
  }

  .value {
    font-size: 28rpx;
    color: #333;
    line-height: 1.5;
  }

  .phone {
    font-size: 28rpx;
    display: inline-flex;
    color: #0091FF;
    align-items: center;

    image {
      width: 30rpx;
      height: 30rpx;
      margin-right: 0rpx;
      padding-top: 2rpx;
    }
  }

  .time-info {
    .time-text {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 5rpx;
    }
  }
}

.form-item {
  padding-bottom: 20rpx;
  position: relative;

  .required {
    color: #ff4757;
    margin-right: 5rpx;
  }

  .optional {
    color: #999;
    font-size: 24rpx;
    margin-left: 10rpx;
  }

  .label {
    font-size: 26rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 8rpx;
    display: inline-block;
  }

  .input {
    padding: 0 20rpx;
    border: 1px solid #e5e5e5;
    border-radius: 8rpx;
    height: 72rpx;
    line-height: 72rpx;
    font-size: 28rpx;
    background-color: #fff;
  }

  .textarea {
    width: 628rpx;
    padding: 20rpx;
    border: 1px solid #e5e5e5;
    border-radius: 8rpx;
    height: 120rpx;
    resize: none;
  }

  .char-count {
    text-align: right;
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
    position: absolute;
    bottom: 28rpx;
    right: 18rpx;

  }

  .input-row {
    display: flex;
    align-items: center;
    border: 1px solid #e5e5e5;
    border-radius: 8rpx;
    padding: 0 20rpx;
    height: 72rpx;
    line-height: 72rpx;

    .input {
      flex: 1;
      border: none;
      padding: 0;
    }

    .arrow-right {
      width: 32rpx;
      height: 32rpx;
      margin-right: -8rpx;
      transform: rotate(-90deg);
    }

    .arrow-down {
      width: 32rpx;
      height: 32rpx;
      margin-right: -8rpx;
    }
  }

}

.radio-group {
  display: flex;

  .radio-item {
    width: 33%;
    padding: 6rpx 0rpx;
    border: 1px solid #e5e5e5;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #666;
    background-color: #fff;
    margin-right: 12rpx;
    text-align: center;

    &.active {
      border-color: #0091FF;
      color: #0091FF;
      // background-color: #f0f8ff;
    }
  }

  .radio-item:last-child {
    margin-right: 0;
  }
}

.floor-input {
  display: flex;
  align-items: center;
  padding-bottom: 20rpx;

  .minus-btn,
  .plus-btn {
    width: 64rpx;
    height: 64rpx;
    border: 1px solid #E9E9E9;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    color: #666;
    background-color: #F6F7FA;
  }

  .floor-value {
    width: 156rpx;
    padding: 0 20rpx;
    height: 64rpx;
    line-height: 64rpx;
    border: 1px solid #E9E9E9;
    text-align: center;
    font-size: 28rpx;
  }
}

.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 20rpx 30rpx;
  background-color: #fff;
  z-index: 99;
  border-top: 1px solid #e5e5e5;

  .btn-secondary,
  .btn-primary {
    flex: 1;
    height: 68rpx;
    line-height: 68rpx;
    text-align: center;
    font-size: 28rpx;
  }

  .btn-secondary {
    background-color: #F5FBFF;
    color: #0091FF;
    border-radius: 4px 0px 0px 4px;

  }

  .btn-primary {
    background-color: #0091FF;
    color: #fff;
    border-radius: 0px 4px 4px 0px;

  }
}

.iconfont {
  font-family: 'iconfont';
}

.placeholder {
  color: #ccc !important;
}
</style>